﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Web;

namespace Common.BaseLibrary
{
    public sealed class ComputerInfoHelper
    {
        /// <summary>
        /// 线程锁
        /// </summary>
        private static object lockObj = new object();
        /// <summary>
        /// 计算机信息工厂
        /// </summary>
        private static ComputerInfoHelper instance;

        #region win32 api extend method
        [DllImport("advapi32.dll")]
        static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern bool CloseHandle(IntPtr handle);

        const int LOGON32_LOGON_INTERACTIVE = 2;
        const int LOGON32_PROVIDER_DEFAULT = 0;
        #endregion  

        public static ComputerInfoHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObj)
                    {
                        if (instance == null)
                        {
                            instance = new ComputerInfoHelper();
                        }
                    }
                }
                return instance;
            }
        }


        /// <summary>
        /// 获取本机CPU 序号
        /// </summary>
        /// <returns></returns>
        public string GetCpuID()
        {

            try
            {
                //获取CPU序列号代码
                string cpuInfo = "";//cpu序列号
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                moc = null;
                mc = null;
                return cpuInfo;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary>
        /// 获取单一主板ID信息
        /// </summary>
        /// <returns></returns>
        public string GetMotherBoardID()
        {
            System.Management.ManagementClass mc = new System.Management.ManagementClass("Win32_BaseBoard");
            ManagementObjectCollection moc = mc.GetInstances();
            string motherBoardID = "";
            foreach (ManagementObject mx in moc)
            {
                motherBoardID = mx.Properties["SerialNumber"].Value.ToString();
            }
            return motherBoardID;
        }

        /// <summary>
        /// 获取本机IP V6 地址
        /// </summary>
        /// <returns></returns>
        public string GetUserHostIPV6()
        {
            try
            {
                System.Net.IPHostEntry myEntry = System.Net.Dns.GetHostEntry
                    (System.Net.Dns.GetHostName());
                string ipAddress = myEntry.AddressList[2].ToString();
                return ipAddress;
            }
            catch (Exception)
            {
                return "无法识别本机IP";
            }


        }

        /// <summary>
        /// 获取本机IP V4 地址
        /// </summary>
        /// <returns></returns>
        public string GetUserHostIPV4()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return "获取本机IP出错:" + ex.Message;
            }

        }


        /// <summary>
        /// 获取CPU数量（核）
        /// </summary>
        /// <returns></returns>
        public int GetCpuCount()
        {
            PerformanceCounter[] counters = new PerformanceCounter[System.Environment.ProcessorCount];
            return counters.Length;
        }

        /// <summary>
        /// 获取本机MAC地址
        /// </summary>
        /// <returns></returns>
        public string GetMacAddress()
        {
            try
            {
                //获取网卡硬件地址
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        mac = mo["MacAddress"].ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return mac;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary>
        /// 获取硬盘ID
        /// </summary>
        /// <returns></returns>
        public string GetDiskID()
        {
            try
            {
                //获取硬盘ID
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                }
                moc = null;
                mc = null;
                return HDid;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary>
        /// 操作系统的登录用户名
        /// </summary>
        /// <returns></returns>
        public string GetUserName()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["UserName"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary>
        /// 获取 PC类型
        /// </summary>
        /// <returns></returns>
        public string GetSystemType()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["SystemType"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary>
        /// 获取物理内存
        /// </summary>
        /// <returns></returns>
        public string GetTotalPhysicalMemory()
        {
            try
            {

                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["TotalPhysicalMemory"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }

        /// <summary>
        /// 获取机器名
        /// </summary>
        /// <returns></returns>
        public string GetComputerName()
        {
            try
            {
                return System.Environment.GetEnvironmentVariable("ComputerName");
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }

        /// <summary>
        /// 获取CPU使用率(即时数据)
        /// </summary>
        /// <returns></returns>
        public List<float> GetUsageRateOfCPU()
        {

            #region 原版读取CPU使用率方法

            //PerformanceCounter[] counters = new PerformanceCounter[System.Environment.ProcessorCount];
            //for (int i = 0; i < counters.Length; i++)
            //{
            //    counters[i] = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
            //}
            ////List<float> cpuUsageRate = new List<float>();
            //while (true)
            //{
            //    for (int i = 0; i < counters.Length; i++)
            //    {
            //        float f = counters[i].NextValue();
            //        //cpuUsageRate.Add(f);
            //        Console.WriteLine("CPU-{0}: {1:f}%", i, f);
            //    }
            //    Console.WriteLine();
            //    System.Threading.Thread.Sleep(1000);
            //}

            #endregion

            PerformanceCounter[] counters = new PerformanceCounter[System.Environment.ProcessorCount];
            for (int i = 0; i < counters.Length; i++)
            {
                counters[i] = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
            }
            List<float> cpuUsageRate = new List<float>();

            for (int j = 0; j < 2; j++)
            {
                for (int i = 0; i < counters.Length; i++)
                {
                    if (j == 0)
                    {
                        float f = counters[i].NextValue();

                    }
                    else
                    {
                        float f = counters[i].NextValue();

                        float result = float.Parse(string.Format("{0:F}", f));
                        cpuUsageRate.Add(result);
                        //Console.WriteLine("CPU-{0}: {1:f}%", i, f);
                    }
                }

                //Console.WriteLine();
                System.Threading.Thread.Sleep(500);
            }



            return cpuUsageRate;
        }

        /// <summary>
        ///  获取性能计数器类别列表
        /// “Cache”（缓存）、“Memory”（内存）、
        /// “Objects”（对象）、“PhysicalDisk”（物理磁盘）、“Process”（进程）、
        /// “Processor/Processor Information”（处理器）、
        /// “Server”（服务器）、“System”（系统）和“Thread”（线程）等类别
        /// </summary>
        /// <returns></returns>
        public List<string> GetCategoryNameList()
        {
            List<string> CategoryNameOfList = new List<string>();
            PerformanceCounterCategory[] myCat2;
            myCat2 = PerformanceCounterCategory.GetCategories();
            for (int i = 0; i < myCat2.Length; i++)
            {
                //Console.WriteLine(myCat2[i].CategoryName);
                CategoryNameOfList.Add(myCat2[i].CategoryName);
            }
            return CategoryNameOfList;
        }

        /// <summary>
        /// 性能计数器的名称
        /// </summary>
        /// <param name="CategoryName"></param>
        /// <returns></returns>
        public string[] GetInstanceNameList(string CategoryName)
        {
            string[] instanceNames;
            ArrayList counters = new ArrayList();
            PerformanceCounterCategory mycat = new PerformanceCounterCategory(CategoryName);
            try
            {
                instanceNames = mycat.GetInstanceNames();
                if (instanceNames.Length == 0)
                {
                    counters.AddRange(mycat.GetCounters());
                }
                else
                {
                    for (int i = 0; i < instanceNames.Length; i++)
                    {
                        counters.AddRange(mycat.GetCounters(instanceNames[i]));
                    }
                }
                //for (int i = 0; i < instanceNames.Length; i++)
                //{
                //    Console.WriteLine(instanceNames[i]);
                //}
                return instanceNames;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 性能计数器类别实例的名称，或者为空字符串 ("")（如果该类别包含单个实例）
        /// </summary>
        /// <param name="CategoryName"></param>
        /// <returns></returns>
        public ArrayList GetCounterNameList(string CategoryName)
        {
            string[] instanceNames;
            ArrayList counters = new ArrayList();
            PerformanceCounterCategory mycat = new PerformanceCounterCategory(CategoryName);
            try
            {
                instanceNames = mycat.GetInstanceNames();
                if (instanceNames.Length == 0)
                {
                    counters.AddRange(mycat.GetCounters());
                }
                else
                {
                    for (int i = 0; i < instanceNames.Length; i++)
                    {
                        counters.AddRange(mycat.GetCounters(instanceNames[i]));
                    }
                }


                return counters;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取总内存数 单位MB
        /// </summary>
        /// <returns></returns>
        public long GetMemoryCount()
        {
            ManagementClass mc = new ManagementClass("Win32_OperatingSystem");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if (mo["TotalVisibleMemorySize"] != null)
                {
                    long memoryCount = long.Parse(mo["TotalVisibleMemorySize"].ToString());
                    //Console.WriteLine("总内存：" + xx);
                    return memoryCount / 1024;
                }
            }
            return 0;
        }

        /// <summary>
        /// 获取可用内存（即时） 单位MB
        /// </summary>
        /// <returns></returns>
        public long GetMemoryFreeNum()
        {
            ManagementClass mc = new ManagementClass("Win32_OperatingSystem");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if (mo["FreePhysicalMemory"] != null)
                {
                    long availablebytes = long.Parse(mo["FreePhysicalMemory"].ToString());
                    //Console.WriteLine("剩余可用内存：" + availablebytes);
                    return availablebytes / 1024;
                }
            }
            return 0;
        }

        /// <summary>
        /// 获取已用内存（即时） 单位MB
        /// </summary>
        /// <returns></returns>
        public long GetMemoryUsedNum()
        {
            ManagementClass mc = new ManagementClass("Win32_OperatingSystem");
            ManagementObjectCollection moc = mc.GetInstances();
            long count = GetMemoryCount();
            foreach (ManagementObject mo in moc)
            {
                if (mo["FreePhysicalMemory"] != null)
                {
                    long availablebytes = long.Parse(mo["FreePhysicalMemory"].ToString());
                    //Console.WriteLine("剩余可用内存：" + availablebytes);
                    return count - (availablebytes / 1024);
                }
            }
            return 0;
        }

        /// <summary>
        /// 获取目标主机的主机名
        /// </summary>
        /// <param name="ipAddress">目标IP地址</param>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>
        public string GetConnectionMachineName(string ipAddress, string userName, string password)
        {
            //string userName = "wangzhenhuanmcse@hotmail.com";//帐号
            //string password = "Pass123.";//密码
            //string host = "127.0.0.1";//输入指定计算机IP或计算机名

            string machineName = "";

            ConnectionOptions connectionOptions = new ConnectionOptions();
            if (ipAddress != "." && ipAddress != "127.0.0.1")
            {
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
            }
            ManagementScope managementScope = new ManagementScope("//" + ipAddress + "/root/cimv2", connectionOptions);
            try
            {
                managementScope.Connect();
                //Console.WriteLine(managementScope.IsConnected.ToString());
                if (managementScope.IsConnected) //判断是否连接上
                {
                    ObjectQuery query = new ObjectQuery("select * from Win32_ComputerSystem");
                    ManagementObjectSearcher search = new ManagementObjectSearcher(managementScope, query);
                    ManagementObjectCollection coll = search.Get();
                    foreach (ManagementObject obj in coll)
                    {
                        //PropertyDataCollection.PropertyDataEnumerator pdc = obj.Properties.GetEnumerator();
                        //while (pdc.MoveNext())
                        //{
                        //    Console.WriteLine(pdc.Current.Name + ":" + pdc.Current.Value);
                        //}
                        //Console.WriteLine("-------------------------------------------");

                        //string hostname = obj["DNSHostName"].ToString();//域主机名
                        //string domain = obj["Domain"].ToString(); //域名
                        machineName = obj["Name"].ToString(); //主机名
                        //string role = "";   //域角色
                        //switch (obj["DomainRole"].ToString())
                        //{
                        //    case "0":
                        //        role = "独立的个人机(Standalone Workstation)";
                        //        break;
                        //    case "1":
                        //        role = "成员工作站(Member Workstation)";
                        //        break;
                        //    case "2":
                        //        role = "单独的服务器(Standalone Server)";
                        //        break;
                        //    case "3":
                        //        role = "成员服务器(Member Server)";
                        //        break;
                        //    case "4":
                        //        role = "备用主机(Backup Domain Controller)";
                        //        break;
                        //    case "5":
                        //        role = "主域控制器(Primary Domain Controller)";
                        //        break;
                        //}
                        //Console.WriteLine("HostName:{0}", hostname);
                        //Console.WriteLine("Domain:{0}", domain);
                        //Console.WriteLine("Name:{0}", name);
                        //Console.WriteLine("Role:{0}", role);
                    }
                }

            }
            catch
            {

            }
            return machineName;
        }


        /// <summary>
        /// 获取目标主机的域名
        /// </summary>
        /// <param name="ipAddress">目标IP地址</param>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>
        public string GetConnectionDomainName(string ipAddress, string userName, string password)
        {
            //string userName = "wangzhenhuanmcse@hotmail.com";//帐号
            //string password = "Pass123.";//密码
            //string host = "127.0.0.1";//输入指定计算机IP或计算机名

            string domainName = "";

            ConnectionOptions connectionOptions = new ConnectionOptions();
            if (ipAddress != "." && ipAddress != "127.0.0.1")
            {
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
            }
            ManagementScope managementScope = new ManagementScope("//" + ipAddress + "/root/cimv2", connectionOptions);
            try
            {
                managementScope.Connect();
                //Console.WriteLine(managementScope.IsConnected.ToString());
                if (managementScope.IsConnected) //判断是否连接上
                {
                    ObjectQuery query = new ObjectQuery("select * from Win32_ComputerSystem");
                    ManagementObjectSearcher search = new ManagementObjectSearcher(managementScope, query);
                    ManagementObjectCollection coll = search.Get();
                    foreach (ManagementObject obj in coll)
                    {
                        //PropertyDataCollection.PropertyDataEnumerator pdc = obj.Properties.GetEnumerator();
                        //while (pdc.MoveNext())
                        //{
                        //    Console.WriteLine(pdc.Current.Name + ":" + pdc.Current.Value);
                        //}
                        //Console.WriteLine("-------------------------------------------");

                        //string hostname = obj["DNSHostName"].ToString();//域主机名
                        domainName = obj["Domain"].ToString(); //域名
                        //machineName = obj["Name"].ToString(); //主机名
                        //string role = "";   //域角色
                        //switch (obj["DomainRole"].ToString())
                        //{
                        //    case "0":
                        //        role = "独立的个人机(Standalone Workstation)";
                        //        break;
                        //    case "1":
                        //        role = "成员工作站(Member Workstation)";
                        //        break;
                        //    case "2":
                        //        role = "单独的服务器(Standalone Server)";
                        //        break;
                        //    case "3":
                        //        role = "成员服务器(Member Server)";
                        //        break;
                        //    case "4":
                        //        role = "备用主机(Backup Domain Controller)";
                        //        break;
                        //    case "5":
                        //        role = "主域控制器(Primary Domain Controller)";
                        //        break;
                        //}
                        //Console.WriteLine("HostName:{0}", hostname);
                        //Console.WriteLine("Domain:{0}", domain);
                        //Console.WriteLine("Name:{0}", name);
                        //Console.WriteLine("Role:{0}", role);
                    }
                }

            }
            catch
            {

            }
            return domainName;
        }


        /// <summary>
        /// 获取目标主机的DNS
        /// </summary>
        /// <param name="ipAddress">目标IP地址</param>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>
        public string GetConnectionDNSHostName(string ipAddress, string userName, string password)
        {
            //string userName = "wangzhenhuanmcse@hotmail.com";//帐号
            //string password = "Pass123.";//密码
            //string host = "127.0.0.1";//输入指定计算机IP或计算机名

            string DNSHostName = "";

            ConnectionOptions connectionOptions = new ConnectionOptions();
            if (ipAddress != "." && ipAddress != "127.0.0.1")
            {
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
            }
            ManagementScope managementScope = new ManagementScope("//" + ipAddress + "/root/cimv2", connectionOptions);
            try
            {
                managementScope.Connect();
                //Console.WriteLine(managementScope.IsConnected.ToString());
                if (managementScope.IsConnected) //判断是否连接上
                {
                    ObjectQuery query = new ObjectQuery("select * from Win32_ComputerSystem");
                    ManagementObjectSearcher search = new ManagementObjectSearcher(managementScope, query);
                    ManagementObjectCollection coll = search.Get();
                    foreach (ManagementObject obj in coll)
                    {
                        //PropertyDataCollection.PropertyDataEnumerator pdc = obj.Properties.GetEnumerator();
                        //while (pdc.MoveNext())
                        //{
                        //    Console.WriteLine(pdc.Current.Name + ":" + pdc.Current.Value);
                        //}
                        //Console.WriteLine("-------------------------------------------");

                        DNSHostName = obj["DNSHostName"].ToString();//域主机名
                        //domainName = obj["Domain"].ToString(); //域名
                        //machineName = obj["Name"].ToString(); //主机名
                        //string role = "";   //域角色
                        //switch (obj["DomainRole"].ToString())
                        //{
                        //    case "0":
                        //        role = "独立的个人机(Standalone Workstation)";
                        //        break;
                        //    case "1":
                        //        role = "成员工作站(Member Workstation)";
                        //        break;
                        //    case "2":
                        //        role = "单独的服务器(Standalone Server)";
                        //        break;
                        //    case "3":
                        //        role = "成员服务器(Member Server)";
                        //        break;
                        //    case "4":
                        //        role = "备用主机(Backup Domain Controller)";
                        //        break;
                        //    case "5":
                        //        role = "主域控制器(Primary Domain Controller)";
                        //        break;
                        //}
                        //Console.WriteLine("HostName:{0}", hostname);
                        //Console.WriteLine("Domain:{0}", domain);
                        //Console.WriteLine("Name:{0}", name);
                        //Console.WriteLine("Role:{0}", role);
                    }
                }

            }
            catch
            {

            }
            return DNSHostName;
        }


        /// <summary>
        /// 获取目标主机的域名权限
        /// </summary>
        /// <param name="ipAddress">目标IP地址</param>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>
        public string GetConnectionDomainRoleName(string ipAddress, string userName, string password)
        {
            //string userName = "wangzhenhuanmcse@hotmail.com";//帐号
            //string password = "Pass123.";//密码
            //string host = "127.0.0.1";//输入指定计算机IP或计算机名

            string domainRoleName = "";

            ConnectionOptions connectionOptions = new ConnectionOptions();
            if (ipAddress != "." && ipAddress != "127.0.0.1")
            {
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
            }
            ManagementScope managementScope = new ManagementScope("//" + ipAddress + "/root/cimv2", connectionOptions);
            try
            {
                managementScope.Connect();
                //Console.WriteLine(managementScope.IsConnected.ToString());
                if (managementScope.IsConnected) //判断是否连接上
                {
                    ObjectQuery query = new ObjectQuery("select * from Win32_ComputerSystem");
                    ManagementObjectSearcher search = new ManagementObjectSearcher(managementScope, query);
                    ManagementObjectCollection coll = search.Get();
                    foreach (ManagementObject obj in coll)
                    {
                        //PropertyDataCollection.PropertyDataEnumerator pdc = obj.Properties.GetEnumerator();
                        //while (pdc.MoveNext())
                        //{
                        //    Console.WriteLine(pdc.Current.Name + ":" + pdc.Current.Value);
                        //}
                        //Console.WriteLine("-------------------------------------------");

                        //DNSHostName = obj["DNSHostName"].ToString();//域主机名
                        //domainName = obj["Domain"].ToString(); //域名
                        //machineName = obj["Name"].ToString(); //主机名
                        //string role = "";   //域角色
                        switch (obj["DomainRole"].ToString())
                        {
                            case "0":
                                domainRoleName = "独立的个人机(Standalone Workstation)";
                                break;
                            case "1":
                                domainRoleName = "成员工作站(Member Workstation)";
                                break;
                            case "2":
                                domainRoleName = "单独的服务器(Standalone Server)";
                                break;
                            case "3":
                                domainRoleName = "成员服务器(Member Server)";
                                break;
                            case "4":
                                domainRoleName = "备用主机(Backup Domain Controller)";
                                break;
                            case "5":
                                domainRoleName = "主域控制器(Primary Domain Controller)";
                                break;
                        }
                        //Console.WriteLine("HostName:{0}", hostname);
                        //Console.WriteLine("Domain:{0}", domain);
                        //Console.WriteLine("Name:{0}", name);
                        //Console.WriteLine("Role:{0}", role);
                    }
                }

            }
            catch
            {

            }
            return domainRoleName;
        }

        /// <summary>
        /// 获取目标服务器的磁盘信息
        /// 返回值为 DataTable
        /// DataTable列包含：
        /// DiskName 盘符
        /// DiskFreeCapacity  剩余空间
        /// DiskCountCapacity  该盘符的总空间
        /// DiskType  盘符类型
        /// 首行 格式为 硬盘名称 ，  硬盘总空间， Null,  磁盘类型
        /// </summary>
        /// <param name="ipAddress">目标IP地址</param>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public DataTable GetHostDiskOfHardDriveCapacity(string ipAddress, string userName, string password)
        {

            DataTable dtOfDiskInfo = new DataTable();
            dtOfDiskInfo.Columns.Add("DiskName", typeof(string));
            dtOfDiskInfo.Columns.Add("DiskFreeCapacity", typeof(string));
            dtOfDiskInfo.Columns.Add("DiskCountCapacity", typeof(string));
            dtOfDiskInfo.Columns.Add("DiskType", typeof(string));

            ConnectionOptions connectionOptions = new ConnectionOptions();
            if (ipAddress != "." && ipAddress != "127.0.0.1")
            {
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
            }
            ManagementScope managementScope = new ManagementScope("//" + ipAddress + "/root/cimv2", connectionOptions);
            try
            {
                managementScope.Connect();
                if (managementScope.IsConnected) //判断是否连接上
                {
                    ObjectQuery query = new ObjectQuery("select * from  Win32_DiskDrive");
                    foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive").Get())
                    {
                        dtOfDiskInfo.Rows.Add(drive["Name"].ToString(), (Convert.ToDouble(drive["Size"]) / (1024 * 1024 * 1024)).ToString("f2") + "G", "", drive["MediaType"].ToString());
                        double size = 0;   //分区容量
                        foreach (ManagementObject partition in new ManagementObjectSearcher(
                            "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"]
                            + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
                        {

                            foreach (ManagementObject disk in new ManagementObjectSearcher(
                                "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
                                 + partition["DeviceID"]
                                 + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
                            {

                                dtOfDiskInfo.Rows.Add(disk["Name"].ToString(), (Convert.ToDouble(disk["Size"]) / (1024 * 1024 * 1024)).ToString("f2") + "G", (Convert.ToDouble(disk["FreeSpace"]) / (1024 * 1024 * 1024)).ToString("f2") + "G", drive["MediaType"].ToString());
                                size += Convert.ToDouble(disk["Size"]) / (1024 * 1024 * 1024);
                            }
                        }

                    }
                }


            }
            catch
            {

            }
            return dtOfDiskInfo;
        }

        /// <summary>
        /// 获取目标服务器系统名称
        /// </summary>
        /// <param name="ipAddress">目标IP地址</param>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public string GetConnectionSystemName(string ipAddress, string userName, string password)
        {
            string systemName = "";

            ConnectionOptions connectionOptions = new ConnectionOptions();
            if (ipAddress != "." && ipAddress != "127.0.0.1")
            {
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
            }
            ManagementScope managementScope = new ManagementScope("//" + ipAddress + "/root/cimv2", connectionOptions);
            try
            {
                managementScope.Connect();
                if (managementScope.IsConnected) //判断是否连接上
                {
                    ObjectQuery query = new ObjectQuery("Select * from Win32_OperatingSystem");

                    ManagementObjectSearcher search = new ManagementObjectSearcher(managementScope, query);

                    foreach (ManagementObject mo in search.Get())
                    {
                        systemName = mo["Caption"].ToString();
                    }

                }
                else
                {
                    systemName = "无法连接";
                }
            }
            catch (Exception)
            {
                systemName = "";
            }
            return systemName;

        }
        
        /// <summary>
        /// 获取客户端的IP地址
        /// </summary>
        /// <returns></returns>
        public string GetClientIp()
        {
            var req = HttpContext.Current.Request;
            string user_IP = string.Empty;
            if (req.ServerVariables["HTTP_VIA"] != null)
            {
                if (req.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                {
                    user_IP = req.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                }
                else
                {
                    user_IP = req.UserHostAddress;
                }
            }
            else
            {
                user_IP = req.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return user_IP;
        }


        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            //ServiceContext.SetThreadPrincipal();  
            WindowsImpersonationContext impersonationContext;

            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }  
        
    }
}